package com.ifonly.activerecord.dialect.db;

import com.ifonly.activerecord.dialect.Dialect;
import com.ifonly.activerecord.helpers.SqlInfo;
import com.ifonly.config.Constants;
import com.ifonly.utils.ArrayUtils;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-18 14:45
 * @since JDK 1.6
 */
public class MysqlDialect extends Dialect {

    @Override
    public String buildTableSql(String tableName) {
        return "SELECT * FROM " + tableName + " WHERE 1=2";
    }

    @Override
    public SqlInfo sql(String sql, int offset, int limit, Object... params) {
        String result = getLimitSql(sql, Constants.SQL_PLACEHOLDER, Constants.SQL_PLACEHOLDER);
        Object[] args;
        if (params == null || params.length == 0) {
            args = new Object[]{offset, limit};
        } else {
            args = ArrayUtils.merge(params, new Object[]{offset, limit});
        }
        return new SqlInfo(result, args);
    }

    /**
     * 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
     * <pre>
     * 如mysql
     * dialect.getLimitSql("select * from user", ":offset", ":limit") 将返回
     * select * from user limit :offset,:limit
     * </pre>
     *
     * @param sql               实际SQL语句
     * @param offsetPlaceholder 分页开始纪录条数－占位符号
     * @param limitPlaceholder  分页纪录条数占位符号
     * @return 包含占位符的分页sql
     */
    public String getLimitSql(String sql, String offsetPlaceholder, String limitPlaceholder) {
        return sql + " limit " + offsetPlaceholder + ", " + limitPlaceholder;
    }

}
